﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using Newtonsoft.Json;

namespace MyFile.Service
{
    public class MethodService
    {
        private static readonly Lazy<MethodService> lazy = new Lazy<MethodService>(() => new MethodService());
        public static MethodService Instance { get { return lazy.Value; } }

        #region 私有变量
        /// <summary>
        /// 临时记录Ip
        /// </summary>
        private string TempIp { get; set; }

        /// <summary>
        /// Ping
        /// </summary>
        private Ping _ping { get; set; } = new Ping();

        /// <summary>
        /// PingReply
        /// </summary>
        private PingReply _reply { get; set; }

        /// <summary>
        /// Ping超时时间
        /// </summary>
        private int _pingTimeOut { get; } = 120;

        /// <summary>
        /// GetWindows方法的临时变量
        /// </summary>
        public string item { get; set; }
        #endregion

        public MethodService()
        {

        }

        #region 获取当前活动窗口并打印
        /// <summary>
        /// 获取当前活动窗口并打印
        /// </summary>
        public void GetWindows()
        {
            if (item != GetActiveApplication())
            {
                item = GetActiveApplication();
                if (item != "")
                {
                    Console.WriteLine($"{DateTime.Now.ToString()}：{item}");
                }
            }
        }
        #endregion

        #region 获取当前活动窗口
        /// <summary>
        /// 获取当前活动窗口
        /// </summary>
        /// <returns></returns>
        public static string GetActiveApplication()
        {
            IntPtr hWnd = GetForegroundWindow();
            StringBuilder text = new StringBuilder(256);
            GetWindowText(hWnd, text, text.Capacity);
            return text.ToString();
        }
        #endregion

        #region 获取一个前台窗口的句柄
        /// <summary>
        /// 获取一个前台窗口的句柄
        /// </summary>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();
        #endregion

        #region 获取窗口文本
        /// <summary>
        /// 获取窗口文本
        /// </summary>
        /// <param name="hWnd">带文本的窗口或控件的句柄</param>
        /// <param name="text">指向接收文本的缓冲区的指针</param>
        /// <param name="count"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
        #endregion

        #region 开始Ping
        /// <summary>
        /// 开始Ping
        /// </summary>
        public void StartPing()
        {
            List<string> ipTemp = GetLocal_IPv4()[0].ToString().Split('.').ToList();
            SetPing($"{ipTemp[0]}.{ipTemp[1]}.{ipTemp[2]}");
        }
        #endregion

        #region 设置Ping
        /// <summary>
        /// 设置Ping
        /// </summary>
        /// <param name="ipBase">网段</param>
        public void SetPing(string ipBase)
        {
            try
            {
                int count = 0;
                for (int i = 1; i < 255; i++)
                {
                    string ip = $"{ipBase}.{i}";
                    _reply = _ping.Send(ip, _pingTimeOut);
                    if (_reply.Status == IPStatus.Success)
                    {
                        Console.Write($"{ip} is {_reply.RoundtripTime}ms\t");
                        count++;
                        if (count % 4 == 0)
                        {
                            Console.WriteLine("");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        #endregion

        #region 发送包含当前公网IPV4的邮件
        /// <summary>
        /// 发送包含当前公网IPV4的邮件
        /// </summary>
        /// <param name="email">接收人邮件地址</param>
        public void SendIP_To_Email(string email)
        {
            //如果临时ip不等于当前ip
            if (TempIp != GetIP())
            {
                //将当前ip赋值TempIP
                TempIp = GetIP();
                //发送邮件
                SetEmail(email, "IPV4地址", TempIp);
            }
        }
        #endregion

        #region 设置邮箱
        /// <summary>
        /// 设置邮箱
        /// </summary>
        /// <param name="email">接收人邮件地址</param>
        /// <param name="zhuTi">邮件主题</param>
        /// <param name="neiRong">邮件内容</param>
        public void SetEmail(string email, string zhuTi, string neiRong)
        {
            MailMessage mail = new MailMessage();

            mail.From = new MailAddress("452412279@qq.com");
            mail.To.Add(email);
            mail.Subject = zhuTi;
            mail.Body = neiRong;
            using (SmtpClient client = new SmtpClient("smtp.qq.com", 587))
            {
                client.Credentials = new System.Net.NetworkCredential("452412279@qq.com", "zafwzsgrrbnpbihc");
                client.EnableSsl = true;
                client.Send(mail);
            }
        }
        #endregion

        #region 获取主机名称
        /// <summary>
        /// 获取主机名称
        /// </summary>
        public string GetHostName()
        {
            string hostname = Dns.GetHostName();
            return hostname;
        }
        #endregion

        #region 创建文件
        /// <summary>
        /// 创建文件
        /// </summary>
        public string CreateFile(string filePath)
        {
            string absolutePath = Path.GetFullPath(filePath);
            try
            {
                if (!File.Exists(absolutePath))
                {
                    File.Create(absolutePath).Close();
                    return $"创建文件{absolutePath}成功";
                }
                else
                {
                    return $"文件{absolutePath}已存在";
                }
            }
            catch (Exception ex)
            {
                return $"创建文件{absolutePath}失败{ex.Message}";
            }
        }
        #endregion

        #region 创建目录
        /// <summary>
        /// 创建目录
        /// </summary>
        public string CreatePath(string relativePath)
        {
            string absolutePath = Path.GetFullPath(relativePath);
            try
            {
                if (!Directory.Exists(absolutePath))
                {
                    Directory.CreateDirectory(absolutePath);
                    return $"创建目录{absolutePath}成功";
                }
                else
                {
                    return $"目录{absolutePath}已存在";
                }
            }
            catch (Exception ex)
            {
                return $"创建目录{absolutePath}失败{ex.Message}";
            }
        }
        #endregion

        #region 获取公网IP
        /// <summary>
        /// 获取公网IP
        /// </summary>
        /// <returns></returns>
        public string GetIP()
        {
            string ip = new WebClient().DownloadString("https://httpbin.org/ip");
            Root root = JsonConvert.DeserializeObject<Root>(ip);
            //Console.WriteLine($"IP地址：{root.origin}");
            return root.origin;
        }
        #endregion

        #region 获取本地IPv4地址
        /// <summary>
        /// 获取本地IPv4地址
        /// </summary>
        /// <returns>返回IPv4地址列表</returns>
        public List<IPAddress> GetLocal_IPv4()
        {
            IPHostEntry localhost = Dns.GetHostByName(GetHostName());
            return localhost.AddressList.ToList();
        }
        #endregion

        #region 获取本地IPV4与IPv6地址
        /// <summary>
        /// 获取本地IPV4与IPv6地址
        /// </summary>
        /// <returns>返回IPv6地址列表</returns>
        public List<IPAddress> GetLocal_IPV4_And_IPv6()
        {
            IPHostEntry localhost = Dns.GetHostEntry(GetHostName());
            return localhost.AddressList.ToList();
        }
        #endregion
    }
    public class Root
    {
        /// <summary>
        /// ip地址
        /// </summary>
        public string origin { get; set; }
    }
}
